package com.hqyj.serviceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqyj.mapper.RoleMapper;
import com.hqyj.mapper.UserMapper;
import com.hqyj.pojo.Role;
import com.hqyj.pojo.User;
import com.hqyj.serviceInf.UserServiceInf;
import com.hqyj.utils.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserServiceInf {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

//    用户名为null或者空字符串查询所有，否则查询对应用户信息
    @Override
    public Map<String, Object> selectUser(int pageNum, int pageSize, String username) {
//        开启分页
        PageHelper.startPage(pageNum, pageSize);
        HashMap<String, Object> map = new HashMap<>();
        List<User> users = userMapper.selectUser(pageNum, pageSize, username);
        PageInfo<User> upi = new PageInfo<>(users);
        map.put("code", 200);
        map.put("userPageInfo", upi);
//        System.out.println(users);
        return map;
    }

//    通过字符串进行模糊查询
    @Override
    public Map<String, Object> selectUserLike(int pageNum, int pageSize, String username) {
        //        开启分页
        PageHelper.startPage(pageNum, pageSize);
        HashMap<String, Object> map = new HashMap<>();
        List<User> users = userMapper.selectUserLike(pageNum, pageSize, username);
        PageInfo<User> upi = new PageInfo<>(users);
        map.put("code", 200);
        map.put("userPageInfo", upi);
        return map;
    }

    //    添加用户
    @Override
    public int insertUser(User user) {
//        如果用户没有确定身份，设置为普通用户
        if(user.getRoles() == null || user.getRoles().size() == 0){
            user = setRole(user);
        }
//        新注册的和管理员添加的用户进行密码加密
        user.setPassword(MD5Util.md5(user.getPassword(), user.getUsername() + MD5Util.salt));
        int flag = userMapper.insertUser(user);
//        如果用户添加成功，添加用户角色
        if(flag > 0){
//            查询到所有身份信息
            List<Role> roles = roleMapper.selectAllRole();
            int id = userMapper.selectUserIdByName(user.getUsername());
//            如果用户身份信息和查询出的一样，在用户与身份的关联表中添加记录
            for(Role r:user.getRoles()){
                for(int i = 0; i < roles.size(); i ++){
                    if(r.getRolename().equals(roles.get(i).getRolename())){
                        roleMapper.insertUserRole(id, roles.get(i).getRoleid());
//                        System.out.println(user1.get(0));
                    }
                }
            }
        }
        return flag;
    }
//    添加即为普通用户
    public User setRole(User user){
        ArrayList<Role> roles = new ArrayList<>();
        Role role = new Role();
        role.setRolename("普通用户");
        roles.add(role);
        user.setRoles(roles);
        return user;
    }

//    删除用户
    @Override
    public int deleteUser(int id) {
        int flag = userMapper.deleteUserById(id);
        if(flag > 0){
            roleMapper.deleteUserRole(id);
        }
        return flag;
    }

//    修改用户
    @Override
    public int updateUser(User user) {
//        修改用户时判断用户密码是否发生修改，如果是就加密用户密码
        User user1 = userMapper.selectUser(1, 1, user.getUsername()).get(0);
        if(!user1.getPassword().equals(user.getPassword())){
            user.setPassword(MD5Util.md5(user.getPassword(), user.getUsername() + MD5Util.salt));
        }
        return userMapper.updateUser(user);
    }

//    通过用户名查找用户id
    @Override
    public int selectIdByUserName(String username) {
        return userMapper.selectUserIdByName(username);
    }

//    通过用户名查询用户，登录实现
    @Override
    public Map<String, Object> selectUserByUserName(String username, String password) {
        Map<String,Object> result = new HashMap<>();
        //获取主体 代表当前用户对象
        Subject subject = SecurityUtils.getSubject();
        //判断用户是否已经登陆过
        if(!subject.isAuthenticated()) {
            //没有认证的用户才要登录
            //使用待认证的用户名和密码创建安全令牌对象
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                subject.login(token);
            } catch (UnknownAccountException e) {
                //用户不存在
                result.put("code", -1);
                result.put("message", username + "不存在");
                return result;
            } catch (IncorrectCredentialsException e) {
                //用户名和密码不匹配
                result.put("code", -2);
                result.put("message", username + "密码错误");
                return result;
            } catch (AuthenticationException e) {
                //其他异常
                e.printStackTrace();
                result.put("code", -3);
                result.put("message", username + "认证失败");
                return result;
            }
        }
        //用户已经通过认证
//        System.out.println(username + "认证通过了");
        //从shiro中提供的session对象中获取已经认证的用户
        Object user = subject.getSession().getAttribute("user");
        result.put("code", 200);
        result.put("message", username + "认证成功");
        result.put("loginUser",user);
        return result;
    }
}
